#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""导出 /api/miniprogram 下当前已注册路由和方法的只读脚本。
改进：
1) 自动添加项目根到 sys.path 防止 ModuleNotFoundError
2) 友好错误输出，不抛未捕获异常
3) 若依赖/应用初始化失败，输出诊断建议
"""
import os, json, sys, traceback, pathlib

ROOT = pathlib.Path(__file__).resolve().parent.parent
if str(ROOT) not in sys.path:
    sys.path.insert(0, str(ROOT))

def main():
    try:
        from backend import create_app
    except Exception as e:
        print('[routes][ERROR] 无法导入 backend 模块:', e)
        print('[routes][HINT] 请确认在项目根目录执行，或虚拟环境已激活。')
        return  # 不写文件

    try:
        app = create_app()
    except Exception as e:
        print('[routes][ERROR] create_app() 执行失败:', e)
        traceback.print_exc()
        print('[routes][HINT] 检查依赖安装、数据库连接、配置文件。')
        return

    snapshot = []
    for rule in app.url_map.iter_rules():
        rule_str = str(rule.rule)
        if rule_str.startswith('/api/miniprogram/'):
            snapshot.append({
                'rule': rule_str,
                'methods': sorted(m for m in rule.methods if m not in ('HEAD','OPTIONS')),
                'endpoint': rule.endpoint
            })
    snapshot = sorted(snapshot, key=lambda x: x['rule'])
    out_dir = ROOT / 'temp_uploads'
    out_dir.mkdir(exist_ok=True)
    path = out_dir / 'miniprogram_routes_snapshot.json'
    with path.open('w', encoding='utf-8') as f:
        json.dump({'routes': snapshot}, f, ensure_ascii=False, indent=2)
    print(f'[routes] snapshot written -> {path} (count={len(snapshot)})')

if __name__ == '__main__':
    main()
